var ctx;
var firstLevel = 1;
var secondLevel = 2;
var firstCategory = '';
var secondCategory = '';

function setCtx(ctx) {
    this.ctx = ctx;
}

var attrNames = new Array();
var initCol = 3;
$(function(){
	initListener();  //添加区域监听事件
		
	var firstRow = $('#attr_spec tr:eq(0) td');
	var flag = firstRow.length - initCol;
	$('#attr_spec tr:eq(0)').find('td').each(function(index){
        if(flag > 0 && index < flag){
            attrNames.push($(this).text());
        }
    });
	$("#selectedTwo").hide();
	$("#selectedThree").hide();
});

//省市区级联
function initListener() {
    $("#firstCategory").change(function () {
        firstCategory = $('#firstCategory').val();
        if (firstCategory != '') {
            $.ajax({
                type : "GET",
                url : ctx + "/goods/getCategoryByParentId",
                cache : false,
                dataType : 'json',
                data : {
                    parentId : firstCategory
                },
                success : function(data) {
                    if (data.success) {
                        var result = "<option value='" + "'>--二级分类--</option>";
                        $.each(data.obj, function(index, item) {
                            result += "<option id='" + item.name + "'" + " value='" + item.id + "'>" + item.name + "</option>";
                        });
                        $("#secondCategory").html('');
                        $("#secondCategory").append(result);
                    }
                }
            });
        } else {
            var result = "<option value='" + "'>--二级分类--</option>";
            $("#secondCategory").html('');
            $("#secondCategory").append(result);
        }
    });
    
//    $('#secondCategory').change(function() {
//        if ($('#secondCategory').val() != 0) {
//            secondCategory = $('#secondCategory').val();
//            if(secondCategory != ''){
//                $.ajax({
//                    type : "POST",
//                    url : ctx + "/goodsInfo/getGoodsAttrByCategoryId",
//                    cache : false,
//                    dataType : 'json',
//                    data : {
//                        categoryId : secondCategory
//                    },
//                    success : function(data) {
//                        if (data.success) {
//                              var jsonObj=eval("("+data.obj+")");  
//                              
//                              var html = "<table style='width:100%; margin-top:0px;table-layout:fixed'><tbody><tr>";
//                                $.each(jsonObj, function (i, item) {
//                                    html += "<input id='attrId"+item.id+"' type='hidden' value="+item.id+" >";
//                                    html += "<th width='10%' style='background-color: #e0eff3;height:40px'>"+item.name+"</th>";
//                                });
//                                html += "<tr></tbody>";
//                                html += "<tbody id='tableTbody'>";
//                                html += "<tr>";
//                                    $.each(jsonObj, function (i, item) {
//                                        if(item.inputType == 1){
//                                            html += "<td><select class='editform-control' style='height: 31px;'>";
//                                            for(var j = 0;j < item.categoryAttrValues.length;j++){
//                                                    html += "<option value="+item.categoryAttrValues[j].id+">"+item.categoryAttrValues[j].name+"</option>";
//                                                    
//                                            }
//                                            html += "</select></td>";
//                                        }else if(item.inputType == 2){
//                                            html += "<td><input class='controlEdit' type='text' maxlength='50' value='11' ></td>";
//                                        }
//                                    });
//                                html += "</tr>";
//                                html += "</tbody></table>";
//                                $("#goodsSpecification").append(html);
//                        }
//                    }
//                });
//            }
//        }
//    });

}

function showdelete(target){
    $(target).children("span").css("display","block");
}

function hidedelete(target){
    $(target).children("span").css("display","none");
}

// 检验商品信息输入
function checkGoodsInfoInput(){
    return checkGoodsName() && checkGoodsCategaryOne() && checkGoodsCategaryTwo()
        && checkPrice() && checkMarketPrice() && checkUnit() && checkStockAmount();
}
function gotoGoodsInfo(target){
    $("#goodsInfo")[0].style.display="block";
    $("#goodsDescrip")[0].style.display="none";
    $("#goodsSpec")[0].style.display="none";
    $("#selected1").attr("src",ctx+"/images/seller/coupon/select_yellow.png");
    $("#selectedOne").show();
    $("#selected2").attr("src",ctx+"/images/seller/coupon/select_blue.png");
    $("#selectedTwo").hide();
    $("#selected3").attr("src",ctx+"/images/seller/coupon/select_blue.png");
    $("#selectedThree").hide();
}

function gotoGoodsDescrip(target){
    var flag = true;
    if($('#goodsInfo').is(':visible')){
        flag = checkGoodsInfoInput();
    }
    if(flag) {
    	$("#goodsDescrip")[0].style.display="block";
    	$("#goodsInfo")[0].style.display="none";
    	$("#goodsSpec")[0].style.display="none";
    	$("#selected2").attr("src",ctx+"/images/seller/coupon/select_yellow.png");
    	$("#selectedOne").hide();
    	$("#selected1").attr("src",ctx+"/images/seller/coupon/select_blue.png");
    	$("#selectedTwo").show();
    	$("#selected3").attr("src",ctx+"/images/seller/coupon/select_blue.png");
    	$("#selectedThree").hide();
    }
}

function gotoGoodsSpec(target){
	var flag = true;
    if($('#goodsInfo').is(':visible')){
        flag = checkGoodsInfoInput();
    }
    if(flag) {
    	$("#goodsSpec")[0].style.display="block";
    	$("#goodsDescrip")[0].style.display="none";
    	$("#goodsInfo")[0].style.display="none";
    	$("#selected3").attr("src",ctx+"/images/seller/coupon/select_yellow.png");
    	$("#selectedOne").hide();
    	$("#selected1").attr("src",ctx+"/images/seller/coupon/select_blue.png");
    	$("#selectedTwo").hide();
    	$("#selected2").attr("src",ctx+"/images/seller/coupon/select_blue.png");
    	$("#selectedThree").show();
    }
}

function checkStartTime(){
    var startTime = $("#startTime").val();
    //解决ie9以下placeholder与value重复的问题
    if(startTime == $("#startTime").attr("placeholder")){
        startTime = "";
    }
    
    var    start = new Date(startTime.replace("-", "/").replace("-", "/"));
    if(startTime == null || startTime == ""){
        layer.tips('秒杀开始时间不能为空!', '#startTime', {
            tips: 3
        });
        return false;
    }else{
        return true;        
    }
}

function checkEndTime(){
    var startTime = $("#startTime").val();
    var    start = new Date(startTime.replace("-", "/").replace("-", "/")); 
    var endTime = $("#endTime").val();
    var    end = new Date(endTime.replace("-", "/").replace("-", "/")); 
    //解决ie9以下placeholder与value重复的问题
    if(startTime == $("#startTime").attr("placeholder")){
        startTime = "";
    }
    if(endTime == $("#endTime").attr("placeholder")){
        endTime = "";
    }
    if(endTime == null || endTime == ""){
        layer.tips('秒杀结束时间不能为空!', '#endTime', {
            tips: 3,
            time:1000
        });
        return false;
    }else if(end < start){
        layer.msg("结束时间应大于起始时间",{
            icon: 3,
            time: 1000 //2秒关闭（如果不配置，默认是3秒）
        });
        return false;
    }else{
        return true;
    }
}

function checkGoodsName(){
    var goodsName = $("#goodsName").val();
    //解决ie9以下placeholder与value重复的问题
    var req = /^\S{1,100}$/;
    if(goodsName == $("#goodsName").attr("placeholder")){
        goodsName = "";
    }
    if(goodsName == null || goodsName == ""){
        layer.tips('请填写商品名称!', '#goodsName', {
            tips: 3,
            time:1000
        });
        return false;
    } else if(!req.test(goodsName)) {
        layer.tips('输入不能超过100个字符!', '#goodsName', {
            tips: 3,
            time:1000
        });
        return false;
    } else{
        return true;
    }
}

function checkGoodsCategaryOne(){
    var firstCategory = $("#firstCategory").val();
    //解决ie9以下placeholder与value重复的问题
    if(firstCategory == $("#firstCategory").attr("placeholder")){
        firstCategory = "";
    }
    if(firstCategory == null || firstCategory == ""){
        layer.tips('请选择一级分类!', '#firstCategory', {
            tips: 3,
            time:1000
        });
        return false;
    }else{
        return true;
    }
}

function checkGoodsCategaryTwo(){
    var secondCategory = $("#secondCategory").val();
    //解决ie9以下placeholder与value重复的问题
    if(secondCategory == $("#secondCategory").attr("placeholder")){
        secondCategory = "";
    }
    if(secondCategory == null || secondCategory == ""){
        layer.tips('请选择二级分类!', '#secondCategory', {
            tips: 3,
            time:1000
        });
        return false;
    }else{
        return true;
    }
}

function checkPrice(){
    var businessPrice = $("#businessPrice").val();
    var req = /^\S{1,11}$/;
   
    //解决ie9以下placeholder与value重复的问题
    if(businessPrice == $("#businessPrice").attr("placeholder")){
        businessPrice = "";
    }
    if(businessPrice == null || businessPrice == ""){
        layer.tips('请填写价格!', '#businessPrice', {
            tips: 3,
            time:1000
        });
        return false;
    }else if(parseInt(businessPrice) < 0){
        layer.tips('价格不能小于0!', '#businessPrice', {
            tips: 3,
            time:1000
        });
        return false;
    } else if(!req.test(businessPrice)) {
        layer.tips('输入不能超过10位!', '#businessPrice', {
            tips: 3,
            time:1000
        });
        return false;
    }else {
        return true;
    }
}

function checkMarketPrice(){
    var marketPrice = $("#marketPrice").val();
    var req = /^\S{1,11}$/;
    //解决ie9以下placeholder与value重复的问题
    if(marketPrice == $("#marketPrice").attr("placeholder")){
        marketPrice = "";
    }
    if(marketPrice == null || marketPrice == ""){
        layer.tips('请填写市场价!', '#marketPrice', {
            tips: 3,
            time:1000
        });
        return false;
    }else if(parseInt(marketPrice) < 0){
        layer.tips('市场价不能小于0!', '#marketPrice', {
            tips: 3,
            time:1000
        });
        return false;
    } else if(!req.test(marketPrice)) {
        layer.tips('输入不能超过10位!', '#marketPrice', {
            tips: 3,
            time:1000
        });
        return false;
    } else {
        return true;
    }
}

function checkUnit(){
    var unit = $("#unit").val();
    var req = /^\S{1,255}$/;
    //解决ie9以下placeholder与value重复的问题
    if(unit == $("#unit").attr("placeholder")){
        unit = "";
    }
    if(unit == null || unit == ""){
        layer.tips('请填写单位!', '#unit', {
            tips: 3,
            time:1000
        });
        return false;
    } else if(!req.test(unit)) {
        layer.tips('输入不能超过255个字符!', '#unit', {
            tips: 3,
            time:1000
        });
        return false;
    }else{
        return true;
    }
}

function checkRecommendLevel() {
    var recommendLevel = $("#recommendLevel").val();
    var req = /^\S{1,12}$/;
    //解决ie9以下placeholder与value重复的问题
    if(recommendLevel == $("#recommendLevel").attr("placeholder")){
        recommendLevel = "";
    }
    if(parseInt(recommendLevel) < 0){
        layer.tips('请填写大于0的数字!', '#recommendLevel', {
            tips: 3,
            time:1000
        });
        $("#recommendLevel").val("");
        return false;
    } else if("" != recommendLevel && null != recommendLevel && undefined != recommendLevel && !req.test(recommendLevel)) {
        layer.tips('输入不能超过11位!', '#recommendLevel', {
            tips: 3,
            time:1000
        });
        return false;
    } else {
        return true;
    }
}

//验证商品库存
function checkStockAmount(){
    var goodsType = $('#type').val();
    var stockAmount = $("#stockAmount").val();
    var req = /^\S{1,12}$/;
    //解决ie9以下placeholder与value重复的问题
    if(stockAmount == $("#stockAmount").attr("placeholder")){
        stockAmount = "";
    }
    if(stockAmount == null || stockAmount == ""){
        layer.tips('商品库存不能为空!', '#stockAmount', {
            tips: 3,
            time:1000
        });
        return false;
    }else if(parseInt(stockAmount) < 0){
        layer.tips('请输入正数!', '#stockAmount', {
            tips: 3,
            time:1000
        });
        return false;
    } else if(!req.test(stockAmount)) {
        layer.tips('输入不能超过11位!', '#stockAmount', {
            tips: 3,
            time:1000
        });
        return false;
    } else{
        return true;
    }
}

//检验新增规格输入
function checkInputSpec(){
    var firstRow = $('#attr_spec tr:eq(0) td');
    var realClo = firstRow.length;
    var specs = new Array();
    $('#attr_spec').find('tr:not(:first)').each(function(){
        $(this).find('td input').each(function(index){
            var flag = firstRow.length - initCol;
            if(flag > 0 && index < flag){
                switch (index) {
                case 0:
                    if(!checkInput(this,'请输入属性名称')){
                        $('#this').focus();
                        return false;
                    }
                    break;
                case 1:
                    if(!checkInput(this,'请输入属性名称')){
                        $('#this').focus();
                        return false;
                    }
                    break;
                case 2:
                    if(!checkInput(this,'请输入属性名称')){
                        $('#this').focus();
                        return false;
                    }
                    break;
                default:
                    break;
                }
            }
        });
        var target = $(this).find('input[name="price"]');
        if(!checkInput(target,'请输入价格')){
            $(target).focus();
            return false;
        }
        target = $(this).find('input[name="stock"]');
        if(!checkInput(target,'请输入库存')){
            $(target).focus();
            return false;
        }
    });
}

//保存或新增方法
function saveGoodsInfo() {
	checkInputSpec();
    var infoList = getSpecValues();
    if(checkGoodsName() && checkGoodsCategaryOne() && checkGoodsCategaryTwo()
            && checkPrice() && checkMarketPrice() && checkStockAmount() && checkUnit()){
        $.ajax({
            type : "POST",
            url : ctx + "/goods/saveOrUpdateGoodsInfo",
            cache : false,
            dataType : 'json',
            contentType : 'application/json;charset=utf-8', //设置请求头信息
            data:JSON.stringify(infoList),
            success : function(result) {
                if (result.success) {
                    layer.msg("操作成功",{
                        icon: 1,
                        time: 3000 //2秒关闭（如果不配置，默认是3秒）
                    },function(){
                        loadContent("/goods/editGoodsInfo");
//                        loadContent("/goods/goodsInfoList");
                    });
                } else {
                    layer.msg("操作失败",{
                        icon: 2
                    });
                }
            }
        });
    }
}

function showDefineAttr(){
    $("#defineAttr").toggle();
}

function hideDefineAttr(){
    $("#defineAttr").hide();
}

//返回上一页
function cancel(){
    loadContent("/goods/goodsInfoList");
}
//只能输入数字、两位小数
function checInputNum(obj) {
    obj.value=(obj.value.match(/\d+(\.\d{0,2})?/)||[''])[0];
}
//只能输入数字
function checInputNumOnly(obj) {
    obj.value=obj.value.replace(/[^\d]/g,'');
}

function checkInput(target, tip){
    var value = $(target).val();
    //解决ie9以下placeholder与value重复的问题
    if(value == $(target).attr("placeholder")){
        value = "";
    }
    if(value == null || value == ""){
        layer.tips(tip, target, {
            tips: 3,
            time:1000
        });
        return false;
    }else{
        return true;
    }
}

function appendRow(){
	if(attrNames.length == 0) {
		layer.msg("请先添加自定义属性",{
            icon: 2,
            time: 1000
        });
        return;
	}
	
    var firstRow = $('#attr_spec tr:eq(0)');
    var appendTd = '';
    if(firstRow.length == 0 ) {
        appendTd += '<td><input type="text" class="add-input"></td>'+
            '<td><input type="text" class="add-input" ></td>';
    } else {
        var firstRowTds = $('#attr_spec tr:eq(0) td');
        for(var i = 0; i < firstRowTds.length; i++) {
            if( i == firstRowTds.length - 1) {
                appendTd += '<td><img id="close" onclick="deleteRow(this);" src="images/delete_green.png" style="margin-right:53px;"/></td>';
            } else if(i == firstRowTds.length - 2) {
                appendTd += '<td><input type="text" name="stock" onkeyup="checInputNumOnly(this)"  class="add-input" /></td>';
            } else if(i == firstRowTds.length - 3) {
                appendTd += '<td><input type="text" name="price" onkeyup="checInputNum(this)"  class="add-input" /></td>';
            } else {
                appendTd += '<td><input type="text"  class="add-input"></td>';
            }
        }
    }
    $('#attr_spec').append('<tr>' + appendTd + '</tr>');
}

function appendCloumn(){
	if($('#attr_spec').is(':hidden')){
        $('#attr_spec').show();
    }
	
    var attrName = $('#attr_name').val();
    if('' == attrName) {
        return;
    }
    if(attrNames.length >= 3) {
        layer.msg("属性达到上限",{
            icon: 2,
            time: 1000
        });
        return;
    }
    if($.inArray(attrName, attrNames) != -1) {
        layer.msg("属性名称已存在",{
            icon: 2,
            time: 1000
        });
        return;
    }
    $('#attr_spec').find('tr').each(function(index){
        if(index == 0) {
            attrNames.push(attrName);
            $(this).prepend('<td class="bg-td" width="150px" style="color:black;font-size: 15px;">'  + attrName + "<img id='close' src='images/guanbi.png' onclick='delete_cloum(this);' >" + '</td>');
        } else {
            $(this).prepend('<td ><input type="text" class="add-input"></td>');
        }
    });
    
}

function delete_cloum(target){
    var current_td=$(target).parent();
    var attrName = $(current_td).text();
    var index=current_td.index();
    $('#attr_spec').find('tr').each(function(){
        $(this).children().eq(index).remove();
    });
    
    attrNames.remove(attrName);
    if(attrNames.length == 0) {
    	$('#attr_spec').find('tr:not(:first)').each(function(index){
    		$(this).remove();
    	});
    }
}

function deleteRow(target){
    $(target).parent().parents('tr').remove();
}

function getSpecValues(){
    var goodsName = $('#goodsName').val();
    var secondCategory = $('#secondCategory').val();
    var businessPrice = $("#businessPrice").val();
    var marketPrice = $("#marketPrice").val();
    var unit = $("#unit").val();
    var keyword = $("#keyword").val();
    var isRecommend = $("#recommendLevel").val();
    //var sort = $('#sort').val();
    var sort = 0;
    var stockAmount = $("#stockAmount").val();
    var goodsId;
    if($('#goodsId').val() != "" && $('#goodsId').val() != undefined){
        goodsId = $('#goodsId').val();
    }else{
        goodsId = 0;
    }
    var container = ue.getContent();
    var imageLogoUrl = $('#imageLogo').val();
    //解决ie9以下placeholder与value重复的问题
    if(goodsName == $("#goodsName").attr("placeholder")){
        goodsName = "";
    }
    if(keyword == $("#keyword").attr("placeholder")){
        keyword = "";
    }
    var vals = [];
    vals = keyword.split('|');
    var length = $("#imgLength").val();
    var imgArr = [];
    for(var i=1;i <= length;i++){
        if($("#imgId" + i).val() != null){
            imgArr.push($("#imgId" + i).val());
        }
    }
    var keywordArr = vals.join(',');//转换为逗号隔开的字符串 
    
    var firstRow = $('#attr_spec tr:eq(0) td');
    var initCol = 3;
    var realClo = firstRow.length;
    
    var specs = new Array();
    $('#attr_spec').find('tr:not(:first)').each(function(){
//    $('#attr_spec').find('tr').each(function(rowIndex){
        var info = {};
        
        info.goodsName = goodsName;
        info.secondCategory = secondCategory;
        info.price = businessPrice;
        info.stockAmount = stockAmount;
        info.marketPrice = marketPrice;
        info.unit = unit;
        info.keyword = keywordArr;
        info.isRecommend = isRecommend;
        info.sort = sort;
        info.goodsId = goodsId;
        info.container = container;
        info.imageLogoUrl = imageLogoUrl;
        info.imgArr = imgArr;
        
        $(this).find('td input').each(function(index){
            var flag = firstRow.length - initCol;
            if(flag > 0 && index < flag){
                switch (index) {
                case 0:
                    info.attr1 = attrNames[0]
                    info.attr1Value = this.value;
                    break;
                case 1:
                    info.attr2 = attrNames[1]
                    info.attr2Value = this.value
                    break;
                case 2:
                    info.attr3 = attrNames[2]
                    info.attr3Value = this.value
                    break;
                default:
                    break;
                }
            }
        });
        info.price = $(this).find('input[name="price"]').val();
        info.stock = $(this).find('input[name="stock"]').val();
        specs.push(info);
    });
    
    if(specs.length == 0) {
    	var info = {};
    	info.goodsName = goodsName;
        info.secondCategory = secondCategory;
        info.stockAmount = stockAmount;
        info.price = businessPrice;
        info.marketPrice = marketPrice;
        info.unit = unit;
        info.keyword = keywordArr;
        info.isRecommend = isRecommend;
        info.sort = sort;
        info.goodsId = goodsId;
        info.container = container;
        info.imageLogoUrl = imageLogoUrl;
        info.imgArr = imgArr;
        
        specs.push(info);
    }
    return specs;
}
